import { createStore } from 'vuex'

export default createStore({
  state: {
    token: localStorage.getItem("token") || '',
    userInfo: JSON.parse(localStorage.getItem("userInfo") || '{}'),
    classList: JSON.parse(localStorage.getItem("classList") || '[]'),
    addressList: JSON.parse(localStorage.getItem("addressList") || '[]'),
    classCount: 0,
  },
  getters: {
    getToken(state) {
      return state.token;
    },
    userName(state) {
      return state.userInfo?.userName
    },
    classCount(state) {
      return state.classCount
    }
  },
  mutations: {
    // 更新用户信息
    updateUserInfo(state, data) {
      const { userInfo, token } = data
      console.log("要更新用户信息了", state, userInfo)
      state.userInfo = userInfo;
      state.token = token
      this.commit("saveUserInfo", data)
    },

    // 持久化存储登录用户信息
    saveUserInfo(state, data) {
      console.log("持久存储用户信息：", data)
      const { userInfo, token } = data
      localStorage.setItem("userInfo", JSON.stringify(userInfo))
      localStorage.setItem("token", token)
    },
    updateClassCount(state, n) {
      state.classCount = n
    }
  },
  actions: {
    // 登录后
    login(state, data) {
      state.commit("updateUserInfo", data)
    },

    setClassCount(state, n) {
      console.log("setClassCount", n)
      state.commit("updateClassCount", n)
    }


  },
  modules: {
  }
})
